package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.dto.DishDto;
import com.itheima.entry.Category;
import com.itheima.entry.Dish;
import com.itheima.entry.DishFlavor;
import com.itheima.pojo.CustomException;
import com.itheima.pojo.R;
import com.itheima.service.CategoryService;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.SplittableRandom;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;


    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping
    public R<String> add(@RequestBody DishDto dto){
        dishService.saveWithFlavor(dto);
        String key="dish_"+dto.getCategoryId()+"_1";
        redisTemplate.delete(key);
        return R.success("添加成功");
    }

    @GetMapping("/page")
    public R<Page> page(Integer page,Integer pageSize,String name){
    /*    Page<DishDto> ipage = new Page<>(page,pageSize);
        Page<Dish> dishIPage = new Page<>(page,pageSize);//构建分页
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();//构建条件
        wrapper.like(StringUtils.isNotEmpty(name),Dish::getName,name);
        wrapper.orderByDesc(Dish::getUpdateTime);
        dishService.page(dishIPage,wrapper);
        long total = dishIPage.getTotal();//总记录数
        List<Dish> records = dishIPage.getRecords();//当前页的列表集合
        ArrayList<DishDto> dishDtos = new ArrayList<>();
        for (Dish record : records) {
            DishDto dto = new DishDto();
            Long categoryId = record.getCategoryId();
            Category byId = categoryService.getById(categoryId);
            BeanUtils.copyProperties(record,dto);
            dto.setCategoryName(byId!=null?byId.getName():"");
            dishDtos.add(dto);
        }

        ipage.setTotal(total);
        ipage.setRecords(dishDtos);
        return R.success(ipage);*/
        Page<Dish> dishPage = new Page<>(page,pageSize);
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.like(StringUtils.isNotEmpty(name),Dish::getName,name);
        dishLambdaQueryWrapper.orderByDesc(Dish::getUpdateTime);
        dishService.page(dishPage,dishLambdaQueryWrapper);
        List<Dish> records = dishPage.getRecords();

        for (Dish record : records) {
            Long categoryId = record.getCategoryId();
            Category byId = categoryService.getById(categoryId);
            record.setCategoryName(byId.getName());
        }
        return R.success(dishPage);
    }

    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id){
        DishDto byIdWithFlavor = dishService.getByIdWithFlavor(id);
        return R.success(byIdWithFlavor);
    }

    @PutMapping
    public R<String> upDate(@RequestBody DishDto dto){
        String key="dish_"+dto.getCategoryId()+"_1";
        dishService.upDateWithFlavor(dto);
        redisTemplate.delete(key);
        return R.success("修改成功");
    }


    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        ArrayList<DishDto> dishDtos = null;
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        dishDtos = (ArrayList<DishDto>) redisTemplate.opsForValue().get(key);

        if (dishDtos!=null){
            return R.success(dishDtos);
        }

        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null ,Dish::getCategoryId,dish.getCategoryId());
        queryWrapper.eq(Dish::getStatus,1);
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

            //select * form dish where cayeid=dish.getcateid;

        List<Dish> list = dishService.list(queryWrapper);

        dishDtos = new ArrayList<>();
        for (Dish dish1 : list) {
            LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(DishFlavor::getDishId,dish1.getId());
            List<DishFlavor> list1 = dishFlavorService.list(wrapper);//select * from DishDFlavor where dish_id=dish1.getId;
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish1,dishDto);
            //dishDto.setFlavors(list1);
            dishDtos.add(dishDto);
        }
        redisTemplate.opsForValue().set(key,dishDtos,60, TimeUnit.MINUTES);
        return R.success(dishDtos);
    }

    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids){
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.in(Dish::getId,ids);
        dishLambdaQueryWrapper.eq(Dish::getStatus,0);
        int count = dishService.count(dishLambdaQueryWrapper);
        if (count>0){
            throw new CustomException("当前菜品正在出售，不能删除");
        }
        dishService.removeByIds(ids);
        return R.success("删除成功");
    }
}
